package com.cy.src.tcpudp.client.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * Created by cy on 16-10-13.
 */

public class UDPClient {


    private String BROACTCAST_HOST = "255.255.255.255";
    private int BROACTCAST_PORT = 8888;

    public UDPClient() {

        try {
            DatagramSocket datagramSocket = new DatagramSocket();

            String helloService = "helloService";
            InetAddress inetAddress = InetAddress.getByName(BROACTCAST_HOST);
            DatagramPacket packet = new DatagramPacket(helloService.getBytes(), helloService.length(), inetAddress, BROACTCAST_PORT);
            datagramSocket.send(packet);


//            接收服务端返回的数据
            byte receiverData[] = new byte[1024];
            DatagramPacket receiverPacket = new DatagramPacket(receiverData, receiverData.length);
            datagramSocket.receive(receiverPacket);


            int offset = receiverPacket.getOffset();
            int length = receiverPacket.getLength();
            String socketAddress = receiverPacket.getSocketAddress().toString();
            String content = new String(receiverPacket.getData(), receiverPacket.getOffset(), receiverPacket.getOffset() + receiverPacket.getLength());

            System.out.println("收到服务器端返回的数据：" + content + "   offset=" + offset + "  length=" + length + "   socketAddress=" + socketAddress);

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        new UDPClient();
    }
}
